<template>
  <div class="workorder">
    <div>
      <Crumbs title="工单管理" />
    </div>
    <div class="main">
      <el-row>
        <el-form :inline="true" :model="formInline">
          <el-form-item>
            <el-select v-model="formInline.orderType" placeholder="工单类型" clearable>
              <el-option label="账号权限类" value="0"></el-option>
              <el-option label="服务类" value="1"></el-option>
              <el-option label="开发类" value="2"></el-option>
              <el-option label="其他" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="formInline.workStatus" placeholder="工单状态" clearable>
              <el-option label="待回复" value="0"></el-option>
              <el-option label="关闭" value="1"></el-option>
              <el-option label="待办" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="formInline.priority" placeholder="优先级" clearable>
              <el-option label="紧急" value="0"></el-option>
              <el-option label="高" value="1"></el-option>
              <el-option label="中" value="2"></el-option>
              <el-option label="低" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="date" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="default" @click="reset">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="createDialogVisible = true">新增</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <div style="max-height: calc(100% - 100px); overflow-y: auto" ref="tableBoxref">
        <el-row >
          <el-table :data="tableData" size="small" highlight-current-row>
            <el-table-column prop="orderNo" label="工单编号" align="center" />
            <el-table-column label="工单类型" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.orderType === '0'">账号权限类</span>
                <span v-if="scope.row.orderType === '1'">服务类</span>
                <span v-if="scope.row.orderType === '2'">开发类</span>
                <span v-if="scope.row.orderType === '3'">其他</span>
              </template>
            </el-table-column>
            <el-table-column prop="orderDesc" label="工单描述" align="center" />
            <el-table-column label="优先级" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.priority === '0'">紧急</span>
                <span v-if="scope.row.priority === '1'">高</span>
                <span v-if="scope.row.priority === '2'">中</span>
                <span v-if="scope.row.priority === '3'">低</span>
              </template>
            </el-table-column>
            <el-table-column prop="createBy" label="创建人" align="center" />
            <el-table-column prop="endDate" label="截止时间" align="center" />
            <el-table-column label="工单状态" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.workStatus === '0'">待回复</span>
                <span v-if="scope.row.workStatus === '1'">关闭</span>
                <span v-if="scope.row.workStatus === '2'">待办</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button @click="handleClick(scope.row)" type="text">流转</el-button>
                &nbsp;&nbsp;
                <el-popconfirm title="是否删除该工单数据？" @confirm="remove(scope.row)">
                  <el-button type="text" slot="reference" :disabled="deleteflat">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </div>

      <p>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChangePage"
          :current-page="formInline.pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="formInline.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </p>
      <!-- 新增弹窗 -->
      <el-dialog title="新增工单" width="30%" :visible.sync="createDialogVisible" @close="resetForm('createDialog')">
        <el-form :model="addformInline" label-width="120px" ref="createDialog" :rules="createrules">
          <el-form-item label="工单类型" prop="orderType">
            <el-select v-model="addformInline.orderType" placeholder="工单类型">
              <el-option label="账号权限类" value="0"></el-option>
              <el-option label="开发类" value="2"></el-option>
              <el-option label="服务类" value="1"></el-option>
              <el-option label="其他" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工单描述" prop="orderDesc">
            <el-input type="textarea" v-model="addformInline.orderDesc" style="width: 225px"></el-input>
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="addformInline.priority" placeholder="优先级">
              <el-option label="紧急" value="0"></el-option>
              <el-option label="高" value="1"></el-option>
              <el-option label="中" value="2"></el-option>
              <el-option label="低" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="截止时间" prop="endDate">
            <div class="block">
              <el-date-picker v-model="addformInline.endDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" :picker-options="expireTimeOption"> </el-date-picker>
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="createDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="create">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 流转弹窗 -->
      <el-dialog title="工单流转" width="70%" :visible.sync="editDialogVisible" @close="resetForm('roamdialog')">
        <div style="margin-left: 20px">
          <h2>工单详情</h2>
        </div>
        <el-form :model="roamformInline" label-width="120px">
          <el-form-item label="工单编号" required>
            <el-input v-model="roamformInline.orderNo" style="width: 350px" disabled> </el-input>
          </el-form-item>
          <el-form-item label="工单类型" required>
            <el-input v-model="roamformInline.orderTypeVal" style="width: 350px" disabled></el-input>
          </el-form-item>
          <el-form-item label="工单描述" required>
            <el-input type="textarea" v-model="roamformInline.orderDesc" style="width: 350px" disabled></el-input>
          </el-form-item>
          <el-form-item label="优先级" required>
            <el-input v-model="roamformInline.priorityVal" style="width: 350px" disabled></el-input>
          </el-form-item>
          <el-form-item label="截止日期" required>
            <el-input v-model="roamformInline.endDate" style="width: 350px" disabled></el-input>
          </el-form-item>
        </el-form>

        <div style="margin-left: 20px">
          <h2>流程轨迹</h2>
        </div>
        <el-form :model="formInline" label-width="120px" style="margin-left: 20px">
          <el-table :data="roamtableData">
            <el-table-column prop="createBy" label="处理人" />
            <el-table-column prop="createdTime" label="处理时间" />
            <el-table-column prop="operType" label="操作">
              <template slot-scope="scope">
                <span v-if="scope.row.operType === '1'">回复</span>
                <span v-if="scope.row.operType === '2'">转派</span>
                <span v-if="scope.row.operType === '3'">关闭</span>
              </template>
            </el-table-column>
            <el-table-column prop="operOpinions" label="操作意见" />
          </el-table>
        </el-form>
        <div v-if="operation == '2'">
          <div style="margin-left: 20px">
            <h2>工单操作</h2>
          </div>
          <el-form :model="roamformInline" label-width="120px" ref="roamdialog" :rules="roamrules">
            <el-form-item label="操作类型" prop="operType">
              <el-select v-model="roamformInline.operType" style="width: 350px" placeholder="" clearable @change="opachange">
                <el-option label="回复" value="1"></el-option>
                <el-option label="转派" value="2" v-if="deleteflat == false"></el-option>
                <el-option label="关闭" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="转派角色" prop="character">
              <el-select v-model="roamformInline.character" style="width: 350px" placeholder="" clearable @change="characterchange" :disabled="reassignment">
                <el-option v-for="item in characteroptions" :key="item.roleId" :label="item.roleName" :value="item.roleId"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="转派用户" prop="roleId">
              <el-select v-model="roamformInline.roleId" style="width: 350px" placeholder="" clearable :disabled="reassignment">
                <el-option v-for="item in roleIdoptions" :key="item.optionValue" :label="item.optionText" :value="item.optionValue"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="操作意见" prop="operOpinions">
              <el-input type="textarea" style="width: 350px" v-model="roamformInline.operOpinions"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="roambtn">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  components: {},
  data () {
    return {
      deleteflat: true,
      //设置失效日期今天之前的日期不可选
      expireTimeOption: {
        disabledDate (date) {
          //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return date.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      roleIdoptions: [],
      characteroptions: [],
      createrules: {
        orderType: [
          { required: true, message: '工单类型不能为空', trigger: 'change' },
        ],
        orderDesc: [
          { required: true, message: '工单描述不能为空', trigger: 'change' },
          { max: 200, message: '长度在200字符内', trigger: 'change' }
        ],
        priority: [
          { required: true, message: '优先级不能为空', trigger: 'change' },
        ],
        endDate: [
          { required: true, message: '截止时间不能为空', trigger: 'change' },
        ],
      },
      roamrules: {
        operType: [
          { required: true, message: '请选择操作类型', trigger: 'change' },
        ],
        character: [
          { required: false, message: '请选择转派角色', trigger: 'change' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'change' }
        ],
        roleId: [
          { required: false, message: '请选择转派用户', trigger: 'change' },
        ],
        operOpinions: [
          { required: true, message: '请输入操作意见', trigger: 'change' },
          { max: 200, message: '长度在 200个字符内', trigger: 'change' }
        ],
      },
      total: 0,
      date: [],
      formInline: {
        orderType: '',
        workStatus: '',
        priority: '',
        // beginDate: '',
        // finishDate: '',
        pageNum: 1,
        pageSize: 10
      },
      addformInline: {
        orderType: '',
        orderDesc: '',
        priority: '',
        endDate: ''
      },
      roamformInline: {
        orderNo: '',
        orderType: '',
        orderDesc: '',
        priority: '',
        endDate: '',
        operType: '',
        character: '',
        roleId: '',
        operOpinions: ''
      },
      roamtableData: [],
      tableData: [],
      multipleSelection: [],
      currentStatus: 1, // 1已审批 0未审批
      createDialogVisible: false, //是否显示新建窗口
      editDialogVisible: false, //是否显示编辑窗口
      operation: '',
      // 转派的控制
      reassignment: true
    };
  },
  created () {
    console.log(this.$store.state)
    // if (this.$store.state.loginUser.userFlag == '0') {
    if (this.$store.state.loginUser.userId == '1') {
      this.deleteflat = false
    }
    this.loadData();
  },
  methods: {
    // 操作类型变化
    opachange (val) {
      console.log(val)
      // 如果是转派
      if (val == '2') {
        // 才填
        this.reassignment = false
        // 校验改变
        this.roamrules.character = [
          { required: true, message: '请选择转派角色', trigger: 'change' },
        ]
        this.roamrules.roleId = [
          { required: true, message: '请选择转派用户', trigger: 'change' },
        ]
      } else {
        this.reassignment = true
        // 清空数据
        this.roamformInline.character = ''
        this.roamformInline.roleId = ''
        // 清空转派校验的文字
        this.$refs.roamdialog.clearValidate(['character', 'roleId'])
        this.roamrules.character = [
          { required: false, message: '请选择转派角色', trigger: 'change' },
        ]
        this.roamrules.roleId = [
          { required: false, message: '请选择转派用户', trigger: 'change' },
        ]
      }
    },
    create () {
      // 校验
      this.$refs['createDialog'].validate((valid) => {
        if (valid) {
          this.$http({
            url: '/api/work/order/',
            method: 'post',
            data: this.addformInline
          }).then(res => {
            // 判断
            if (res.data.code == 200) {
              this.$message.success('工单提交成功!')
              this.$refs['createDialog'].resetFields()
              this.createDialogVisible = false
              this.loadData()
            } else {
              this.$message.error('工单提交失败!')
            }

          }).catch(err => {
            this.$message.error('工单提交失败!')
          })
        }
      });

    },
    onSubmit () {
      this.formInline.pageNum = 1
      this.loadData()
    },
    reset () {
      this.formInline.orderType = ""
      this.formInline.workStatus = ""
      this.formInline.priority = ""
      // this.formInline.beginDate = ""
      // this.formInline.finishDate = ""
      this.date = []
      this.formInline.pageNum = 1
      this.loadData()
    },
    handleCurrentChange (pageNo) {
      //当前页发生变化
      this.formInline.currentPage = pageNo;
      this.loadData();
    },
    loadData () {
      this.formInline.beginDate = this.date[0]
      this.formInline.finishDate = this.date[1]
      this.$http({
        url: '/api/work/order/list',
        method: 'GET',
        params: this.formInline
      }).then(res => {
        this.tableData = res.data.rows
        this.total = res.data.total
      })
    },
    // 监听分页pagesize改变函数
    handleSizeChange (newSize) {
      // 滚动条置顶
      console.log(this.$refs.tableBoxref.scrollTop)
      this.$refs.tableBoxref.scrollTop = 0
      this.formInline.pageNum = 1
      this.formInline.pageSize = newSize
      this.loadData()
    },
    // 监听怕个pagenum改变函数
    handleCurrentChangePage (newPage) {
      this.formInline.pageNum = newPage
      this.loadData()
    },
    handleClick (row) {
      // 获取数据
      this.$http({
        url: `/api/work/order/${row.orderNo}`,
        method: 'get',
      }).then(res => {
        this.editDialogVisible = true;
        this.roamformInline.orderNo = res.data.data.orderNo
        this.roamformInline.orderTypeVal = res.data.data.orderTypeVal
        this.roamformInline.orderDesc = res.data.data.orderDesc
        this.roamformInline.priorityVal = res.data.data.priorityVal
        this.roamformInline.endDate = res.data.data.endDate
        switch (res.data.data.orderType) {
          case '0':
            this.roamformInline.orderTypeVal = '账号权限类'
            break;
          case '1':
            this.roamformInline.orderTypeVal = '服务类'
            break;
          case '2':
            this.roamformInline.orderTypeVal = '开发类'
            break;
          case '3':
            this.roamformInline.orderTypeVal = '其他'
            break;
        }

        switch (res.data.data.priority) {
          case '0':
            this.roamformInline.priorityVal = '紧急'
            break;
          case '1':
            this.roamformInline.priorityVal = '高'
            break;
          case '2':
            this.roamformInline.priorityVal = '中'
            break;
          case '3':
            this.roamformInline.priorityVal = '低'
            break;
        }
        this.roamtableData = res.data.data.workOrderTrackList
        this.operation = res.data.data.workStatus
        // console.log(this.operation)

      })
      this.$http({
        url: `/api/system/userRole/selectRoleList`,
        method: 'get',
      }).then(res => {
        this.characteroptions = res.data.data
      })
    },
    roambtn () {
      let data = {
        // 创建人id
        operOpinions: this.roamformInline.operOpinions,
        operType: this.roamformInline.operType,
        orderNo: this.roamformInline.orderNo,
        // 用户id
        roleId: this.roamformInline.roleId,
        // 转派来源，0：工单 1：资源 2：开发者认证
        source: '0'
      }
      console.log(this.$refs['roamdialog'])
      if (this.$refs['roamdialog'] !== undefined) {
        this.$refs['roamdialog'].validate((valid) => {
          if (valid) {
            this.$http({
              url: '/api/work/track',
              method: 'post',
              data: data
            }).then(res => {
              if (res.data.code == 200) {
                // this.$refs['createDialog'].resetFields()
                this.editDialogVisible = false
                this.loadData()
              } else {
                this.$message.error('流转失败')
              }
            })
          }
        });
      } else {
        this.editDialogVisible = false
      }

    },
    remove (data) {
      this.$http({
        url: `/api/work/order/delete/${data.orderNo}`,
        method: 'GET',
      }).then(res => {
        this.loadData()
      })
    },
    resetForm (form) {
      // console.log(form)
      // 判断有无这个dialog
      if (this.operation == '2') {
        this.$refs[form].resetFields()
      }
    },
    characterchange (val) {
      this.roamformInline.roleId = ''
      if (val === '') {
        this.roleIdoptions = []
      } else {
        this.$http({
          url: `/api//system/userRole/selectRoleUserList/${val}`,
          method: 'get',
        }).then(res => {
          this.roleIdoptions = res.data.data
        })
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.workorder {
  height: calc(100vh - 100px);
  background-color: #f8f8f8;
  padding: 5px 30px 10px;

  .main {
    position: relative;
    height: 92%;
    background-color: white;
    // overflow-y: auto;
    box-sizing: border-box;
    padding: 20px;
  }
}
</style>
